package net.rock.utils;

import net.rock.pojo.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class ServiceCaller {
    static final int ADMIN_PERMISSION = 1;

    @Autowired
    private RestTemplate restTemplate;

    public User fetchUserBySessionId(String sessionId) {
        return restTemplate.getForObject(
                "http://userservice/inter-service/user/fetchBySessionId?sessionId=" + sessionId,
                User.class
        );
    }

    public User fetchUserById(int id) {
        return restTemplate.getForObject(
                "http://userservice/inter-service/user/fetchById?id=" + id,
                User.class
        );
    }

    @SuppressWarnings("BooleanMethodIsAlwaysInverted")
    public boolean checkAdmin(String sessionId) {
        if (StringUtils.isEmpty(sessionId)) {
            return false;
        }
        User user = fetchUserBySessionId(sessionId);
        return user.getPermission() >= ADMIN_PERMISSION;
    }
}
